//
//  SearchTableViewController.m
//  MingShi
//
//  Created by MJiao on 15/6/30.
//  Copyright (c) 2015年 MJiao. All rights reserved.
//

#import "SearchTableViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "KVNProgress.h"
#import "SearchResult.h"
#import "MySeachResultTableViewCell.h"
#import "CommonUtils.h"
#import "UIImageView+AFNetworking.h"
#import "UserManager.h"
#import "SNSViewController.h"

@interface SearchTableViewController ()
@property(nonatomic, strong) NSMutableArray *dataArray;
@end

@implementation SearchTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.dataArray = [[NSMutableArray alloc] init];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [self.dataArray count];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SearchResult *searchResult = self.dataArray[indexPath.row];

    NSString *string = [NSString stringWithFormat:@"您确定要关注%@吗?", searchResult.userName];

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:string delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    alert.alertViewStyle = UIAlertViewStyleDefault;
    [alert show];
    
    self.selectedSearResult = searchResult;
    
}


// Called when a button is clicked. The view will be automatically dismissed after this call returns
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    //取消上次选择中的被选择效果
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:NO];
    
    if (buttonIndex != 0) {
        return;
    }
    // Adds a status below the circle
  //  [KVNProgress showWithStatus:@"请求中..."];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

 
    NSString *urlString = [NSString stringWithFormat:@"http://121.41.91.36:8888/api/uid/payAttent?userId=%ld&fid=%ld", [[UserManager shareUserManager]
            curUser].userId,
    self.selectedSearResult.userId];


    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        // 结束登陆提示
       // [KVNProgress dismiss];

        NSString *code = [responseObject objectForKey:@"code"];
        //登录失败
        if (code == nil || ![code isEqualToString:@"00"]) {
            [KVNProgress showErrorWithStatus:[responseObject objectForKey:@"msg"]];
            return;
        }

        [KVNProgress showSuccessWithStatus:[responseObject objectForKey:@"msg"] completion:^{
            UIViewController *rootViewController = [self.navigationController.viewControllers firstObject];
            if([rootViewController isKindOfClass:SNSViewController.class]){
                SNSViewController* snsViewController = (SNSViewController* )rootViewController;
                //更新标识符，让ProfileViewController重新加载数据
                [snsViewController setIsLoadedData:NO];
            }
            // Things you want to do after the HUD is gone.
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
    }    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        // 结束登陆提示
        [KVNProgress dismiss];
        [KVNProgress showErrorWithStatus:@"网络异常,请稍后再试"];
    }];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"MySeachResultTableViewCell";
    MySeachResultTableViewCell *seachResultTableViewCell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (seachResultTableViewCell == nil) {
        seachResultTableViewCell = [[MySeachResultTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    // Configure the cell...
    SearchResult *searchResult = [self.dataArray objectAtIndex:[indexPath row]];
    NSString *userName = [CommonUtils serializableIdObject:searchResult.userName defaultValue:@"这家伙很懒,昵称都没修改"];
    [seachResultTableViewCell.lbNickName setText:userName];

    NSString *userImage = [CommonUtils serializableIdObject:searchResult.imageUrl defaultValue:@""];
    NSURL *imageURL = [NSURL URLWithString:userImage];
    [seachResultTableViewCell.ivAvatar setImageWithURL:imageURL placeholderImage:[UIImage imageNamed:@"defaultAvatar"]];

    return seachResultTableViewCell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)btnSearchAction:(id)sender {

    NSString *keWord = self.tfSearch.text;

    if (keWord == nil || keWord.length == 0) {
        [KVNProgress showErrorWithStatus:@"请输入查询条件"];
        [self.tfSearch becomeFirstResponder];
        return;
    }

    [self.tfSearch resignFirstResponder];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

    keWord = [keWord stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSString *urlString = [NSString stringWithFormat:@"http://121.41.91.36:8888/api/uid/queryname?loingName=%@", keWord];

    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        // 结束登陆提示
        [KVNProgress dismiss];

        [self.dataArray removeAllObjects];

        NSString *code = [responseObject objectForKey:@"code"];
        //登录失败
        if (code != nil && [code isEqualToString:@"00"]) {
            //  [KVNProgress showErrorWithStatus:[responseObject objectForKey:@"msg"]];
            NSArray *result = [responseObject objectForKey:@"result"];
            [result enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                NSInteger userId = [[obj objectForKey:@"id"] intValue];
                NSString *userName = [obj objectForKey:@"userName"];
                NSString *imageUrl = [obj objectForKey:@"imageUrl"];

                SearchResult *searchResult = [[SearchResult alloc] init];
                searchResult.userId = userId;
                searchResult.userName = userName;
                searchResult.imageUrl = imageUrl;

                [self.dataArray addObject:searchResult];
            }];
            [self.tableView reloadData];
        } else {
            [KVNProgress showErrorWithStatus:[responseObject objectForKey:@"msg"]];
        }


    }    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        // 结束登陆提示
        [KVNProgress dismiss];
        [KVNProgress showErrorWithStatus:@"网络异常,请稍后再试"];
    }];
}
@end
